﻿using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Animation;

namespace Utils.Wpf
{
	public partial class MultiStateLabel : UserControl
	{
		#region Dependency Properties

		private static readonly DependencyPropertyKey StatesPropertyKey = DependencyProperty.RegisterReadOnly("States", typeof(ObservableCollection<LabelState>), typeof(MultiStateLabel), new FrameworkPropertyMetadata(new ObservableCollection<LabelState>()));
		public static DependencyProperty StatesProperty = StatesPropertyKey.DependencyProperty;

		public ObservableCollection<LabelState> States
		{
			get
			{
				return (ObservableCollection<LabelState>)base.GetValue(StatesProperty);
			}
			set
			{
				base.SetValue(StatesProperty, value);
			}
		}

		public static DependencyProperty ActiveStateProperty = DependencyProperty.Register("ActiveState", typeof(int), typeof(MultiStateLabel), new FrameworkPropertyMetadata(OnActiveStatePropertyChanged));

		private static void OnActiveStatePropertyChanged(DependencyObject source, DependencyPropertyChangedEventArgs e)
		{
			MultiStateLabel label = (MultiStateLabel) source;
			label.LoadActiveValues();
		}

		public int ActiveState
		{
			get
			{
				return (int)base.GetValue(ActiveStateProperty);
			}
			set
			{
				base.SetValue(ActiveStateProperty, value);
			}
		}

		#endregion

		#region Public Methods

		public MultiStateLabel()
		{
			ObservableCollection<LabelState> states = new ObservableCollection<LabelState>();
			this.SetValue(MultiStateLabel.StatesPropertyKey, states);
			states.CollectionChanged += States_CollectionChanged;

			InitializeComponent();
		}

		#endregion

		#region Event Handlers

		private void States_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
		{
			if (e.Action == NotifyCollectionChangedAction.Add)
			{
				LabelState state = (LabelState)e.NewItems[0];
				this.AddLogicalChild(state);
				
				if (state.Id == this.ActiveState)
				{
					this.LoadActiveValues();
				}
			}
		}

		#endregion

		#region Private Methods

		private void LoadActiveValues()
		{
			LabelState state = this.States.First(l => l.Id == this.ActiveState);

			this.Border.BorderBrush = state.BorderBrush;
			this.Border.Background = state.Brush;
			this.TextBlock.Background = state.Brush;
			this.TextBlock.Text = state.Text;

			Storyboard storyboard = (Storyboard)FindResource("BlinkAnimation");
			if (state.EnableBlink)
			{
				storyboard.Begin();
			}
			else
			{
				storyboard.Stop();				
			}
		}
		
		#endregion
	}

}
